<template>
  <div class="animate__animated animate__fadeIn">
    <el-card>
      <!--查询部分-->
      <div class="top-container">
        <!--搜索部分-->
        <div class="search-container" v-show="searchShow">
          <el-input
              style="width: 25%;margin-right: 10px"
              placeholder="请输入用户名称..."
              size="small"
              prefix-icon="el-icon-search"
              clearable
              @clear="clearUserName"
              v-model="searchCondition.userName">
          </el-input>
          <el-input
              style="width: 25%;margin-right: 10px"
              placeholder="请输入用户昵称..."
              size="small"
              prefix-icon="el-icon-search"
              clearable
              @clear="clearUserName"
              v-model="searchCondition.nickName">
          </el-input>
          <el-select v-model="searchCondition.gender"
                     clearable
                     size="small"
                     @clear="clearConsumerStatus"
                     placeholder="请选择性别">
            <el-option :key=true label="男" :value="1"/>
            <el-option :key="false" label="女" :value="0"/>
          </el-select>
          <el-button type="primary"
                     size="small"
                     icon="el-icon-search"
                     @click="searchConsumer"
                     style="margin-left: 10px">搜索
          </el-button>
        </div>
        <!--添加部分-->
        <div class="save-container">
          <!--添加-->
          <div class="save-box">
            <el-button type="primary" size="small" plain icon="el-icon-plus" @click="saveConsumerVisible = true">添加用户
            </el-button>
          </div>
          <!--关闭-->
          <div class="close-box">
            <el-tooltip content="关闭查询" placement="bottom">
              <el-button type="primary" size="small" plain circle icon="el-icon-search"
                         @click="searchShow = !searchShow"/>
            </el-tooltip>
            <el-tooltip content="刷新数据" placement="bottom">
              <el-button type="success" size="small" plain circle icon="el-icon-refresh" @click="initData"/>
            </el-tooltip>
            <el-tooltip content="显隐列" placement="bottom">
              <el-button type="warning" size="small" plain circle icon="el-icon-menu" @click="transferVisible = true"/>
            </el-tooltip>
          </div>
        </div>
      </div>
      <!--数据部分-->
      <el-table
        ref="ConsumerTable"
        :data="consumerList"
        style="width: 100%;margin-top: 10px"
        row-key="userId"
        lazy
        highlight-current-row
        v-loading="loading"
        >
      <el-table-column
          v-if="!transferConsumerValue.includes('用户名')" prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('昵称')" align="center" prop="nickname" width="150" label="昵称">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('性别')" prop="gender" label="性别" width="50">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('电话')" align="center" prop="phonenum" min-width="100" label="电话">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('邮箱')" align="center" prop="email" min-width="100" label="邮箱">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('创建人')" min-width="140" align="center" prop="createBy" label="创建人">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('创建时间')" align="center" width="180" label="创建时间">
          <template slot-scope="scope">
            <el-icon class="el-icon-time"/>
            {{ scope.row.gmtCreate }}
          </template>
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('修改人')" align="center" prop="updateBy" min-width="140" label="修改人">
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('修改时间')" align="center" width="180" label="修改时间">
          <template slot-scope="scope">
            <el-icon class="el-icon-time"/>
            {{ scope.row.gmtUpdate }}
          </template>
      </el-table-column>
      <el-table-column
          v-if="!transferConsumerValue.includes('备注信息')" align="center" prop="remark" min-width="180" label="备注信息">
      </el-table-column>
      <el-table-column align="center" min-width="179px" label="操作">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="updateConsumer(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" @click="deleteConsumer(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-card>
    <!--显隐列 弹出层-->
    <el-dialog
        title="显隐列设置"
        :visible.sync="transferVisible"
        width="45%"
        append-to-body
        center>
      <el-transfer
          v-model="transferConsumerValue"
          :data="transferConsumerData"
          :titles="transferConsumerTitles">
      </el-transfer>
    </el-dialog>
    <!--新增 弹出层-->
    <el-drawer
        :title="consumerForm.userId === ''?'新增用户':'修改用户'"
        :visible.sync="saveConsumerVisible"
        append-to-body
        direction="rtl"
        size="28%"
        :before-close="leave">
      <div class="save-container">
        <el-form ref="consumerFormCheck" :rules="rule" :model="consumerForm" label-width="90px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="consumerForm.username" border label="consumer"
                      placeholder="请输入用户名..."/>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="consumerForm.nickname" border label="consumer" placeholder="请输入昵称..."/>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-input v-model="consumerForm.gender" border label="consumer" placeholder="请输入性别..."/>
          </el-form-item>
          <el-form-item label="电话" prop="phonenum">
            <el-input v-model="consumerForm.phonenum" border label="consumer" placeholder="请输入电话..."/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="consumerForm.email" border label="consumer" placeholder="请输入邮箱..."/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="consumerForm.password" border label="consumer" placeholder="请输入密码..."/>
          </el-form-item>
          <el-form-item label="备注信息" align="center">
            <el-input type="textarea" :rows="3" placeholder="请输入备注信息..." v-model="consumerForm.remark"/>
          </el-form-item>
          <el-form-item align="center">
            <el-button icon="el-icon-sunny" size="small" type="success" plain @click="saveConsumerInfo('consumerFormCheck')">
              确定
            </el-button>
            <el-popconfirm
                style="margin-left: 10px"
                title="确定要重置用户信息吗？"
                @confirm="clearForm">
              <el-button icon="el-icon-refresh" size="small" type="warning" plain slot="reference">重置</el-button>
            </el-popconfirm>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {messageInfo} from "@/utils/MessageInfo";
import {
  deleteConsumerById,
  listConsumer,
  listConsumerByCondition,
  saveConsumer,
  updateConsumer
} from "@/api/perm/user/userApi";
import {resultCheck} from "@/utils/result";
import {transferConsumerData, transferConsumerTitles} from "@/assets/const/consumer";
import {isvalidPhone} from "@/utils/validate";

export default {
  name: "Consumer",
  data(){
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return{
      //=======================  表单信息  ===========================
      consumerList: [],
      loading: true,      //表单加载
      searchShow: true,   //查询功能是否开启
      searchCondition: {   //查询条件
        userName: '',
        nickName: '',
        gender:'',
      },
      //=======================  穿梭表单  ===========================
      transferConsumerTitles: transferConsumerTitles(),  //穿梭表单title
      transferConsumerValue: ['创建时间','创建人', '修改人', '修改时间', '备注信息'],               //穿梭表单选中数据
      transferConsumerData: transferConsumerData(),      //穿梭表单数据
      transferVisible: false,            //显隐列是否开启


      //=======================  用户  ===========================
      saveConsumerVisible: false,   //新增用户

      rule: {
        username: [
            {required: true, message: '用户名不能为空！', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
            {required: true, message: '昵称不能为空！', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phonenum: [
            {required: true, trigger: 'blur',validator: validPhone},

        ],
        email:    [
            {required: true, message: '邮箱不能为空！', trigger: 'blur'},
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [{required: true, message: '密码不能为空！', trigger: 'blur'}],
      },
      consumerForm: {
        userId: '',
        username: '',
        nickname: '',
        gender: '',
        phonenum: '',
        email: '',
        password: '',
        remark: ''
      }
    }

  },
  mounted() {
    this.initData();
  },
  methods: {
    //=======================  查询用户部分  ===========================
    initData() {
      this.loading = true;
      listConsumer().then(res => {
        if (res.status) {
          this.consumerList = res.data;
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = false;
      });
    },
    //  清空菜单名称
    clearUserName() {
      this.initData();
    },
    // 清空用户状态
    clearConsumerStatus() {
      this.initData();
    },
    //  查询用户信息
    searchConsumer() {
      if (this.searchCondition.username !== '') {
        listConsumerByCondition(this.searchCondition).then(res => {
          this.consumerList = resultCheck(res, true);
        });
      } else {
        messageInfo({type: 'warning', message: '用户名不能为空哦！'});
      }
    },


    //=======================  新增/修改用户部分  ===========================
    leave() {
      this.$confirm('数据不会临时保存，切勿离开此界面！')
          .then(_ => {
            this.consumerForm = {userId: ''};
            this.saveConsumerVisible = false;
          });
    },
    //  清空表单信息
    clearForm() {
      this.consumerForm = {userId: ''};
    },
    //  添加用户
    saveConsumerInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.consumerForm.userId === '') {
            saveConsumer(this.consumerForm).then(res => {
              resultCheck(res, true);
            });
          } else {
            updateConsumer(this.consumerForm).then(res => {
              resultCheck(res, true);
            });
          }
          this.initData();
          this.saveConsumerVisible = false;
        }
      });
    },

    //  跳转至修改界面
    updateConsumer(data) {
      this.consumerForm = data;
      this.saveConsumerVisible = true;
    },

    //=======================   删除用户 ===========================
    deleteConsumer(data) {
      this.$confirm(`确认要删除名称为： <strong>${data.username}</strong> 的用户吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(_ => {
        deleteConsumerById(data.userId).then(res => {
          resultCheck(res, true);
          this.initData();
          //initConsumer(this.$router, this.$store);
        });
      });
    },
  }

}
</script>

<style>
  .top-container {
    width: 100%;
  }

  .search-container {
    width: 100%;
    display: flex;
    justify-content: left;
  }

  .save-container {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
  }
</style>
